import 'package:get/get.dart';
import 'package:sainbainu/common/apis/account_api.dart';
import 'package:sainbainu/common/apis/user_api.dart';
import 'package:sainbainu/common/models/response/my_account.dart';
import 'package:sainbainu/common/models/response/user_info.dart';
import 'package:sainbainu/common/repositories/account_repository.dart';
import 'package:sainbainu/common/repositories/user_repository.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

class UserService extends GetxService {
  static UserService get to => Get.find();

  UserService();

  /// token
  String? _token;
  String? get token => _token;

  /// 是否登陆
  final _isLogin = false.obs;
  RxBool get isLogin => _isLogin;

  /// 账号仓库
  final AccountRepository _accountRepository = AccountRepository(AccountApi());

  /// 用户数据
  final _accountInfo = MyAccountResponse().obs;
  Rx<MyAccountResponse> get accountInfo => _accountInfo;

  @override
  void onInit() {
    super.onInit();
    // 本地获取 token
    _token = StorageService.to.getString(StorageKeys.token);
    // 本地获取是否登陆
    _isLogin.value = StorageService.to.getBool(StorageKeys.isLogin) ?? false;
    // 拉取账号信息
    if (_isLogin.value) {
      getAccountInfo();
    }
  }

  /// 设置 token
  void setToken(String? value) {
    _token = value;
    if (value != null) {
      StorageService.to.setString(StorageKeys.token, value);
    } else {
      StorageService.to.remove(StorageKeys.token);
    }
  }

  /// 设置是否登陆
  void setIsLogin(bool value) {
    _isLogin.value = value;
    StorageService.to.setBool(StorageKeys.isLogin, value);
  }

  /// 获取账号信息
  Future<void> getAccountInfo() async {
    var accountInfo = await _accountRepository.myAccountInfo();
    _accountInfo.value = accountInfo;
  }
}
